package no.nordicsemi.android.nrftoolbox;

import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateResultAdapter extends BaseAdapter {

    Map<String,String> result = new HashMap<>();
    List<Result> resultList = new ArrayList<Result>();
    List<Result> filtedResult = new ArrayList<Result>();




    UpdateResultAdapter() {}

    @Override
    public int getCount() {
        return resultList.size();
    }

    public int getItemCount() {
        return filtedResult.size();
    }

    @Override
    public Object getItem(int position) {
        if(filtedResult.size() == 0 || position >= filtedResult.size())
            return null;
        else
            return filtedResult.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView( final int position, final View convertView, final ViewGroup parent) {
        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = convertView;
        if(getItem(position) == null)
            view = inflater.inflate(R.layout.dev_list_empty, parent, false);
        else /*if(view == null)*/ {
            view = inflater.inflate(R.layout.dev_lst_upd_rst,parent,false);
            final  ViewHolder holder = new ViewHolder();
            holder.name = view.findViewById(R.id.update_device_name);
            holder.address = view.findViewById(R.id.update_device_address);
            holder.result = view.findViewById(R.id.updatedevice_status);
            view.setTag(holder);
            final Result result = (Result) getItem(position);
            Log.d("RESULT", JSON.toJSONString(result));
            final ViewHolder holde = (ViewHolder) view.getTag();
            final String name = result.getDevName();
            Log.d("HOLDER",String.valueOf(holde == null));
            Log.d("HOLDER",String.valueOf(holde.name == null));
            holde.name.setText(name != null ? name : parent.getContext().getString(R.string.not_available));
            holde.address.setText(result.getDevMac());
            holde.result.setText(result.getDevRsult());
        }
        return view;
    }

    private class ViewHolder {
        public  TextView name;
        public  TextView address;
        public TextView result;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void filtList(String keyword) {
        if(keyword == null) {
            Log.d("KEYWORD", "Is NULL");
            keyword = "";
        }

        //List<ExtendedBluetoothDevice> ret = new ArrayList<>();

        String[] arr = keyword.split(" ");
        filtedResult.clear();
        for(Result result : resultList) {

            //listValues.clear();
            String name = (result.getDevName() == null) ? "N/A" : result.getDevName().toUpperCase();
            String mac = result.getDevMac();
            String status = result.getDevRsult();
            boolean isTarget = true;
            for(String key : arr) {
                if(!name.contains(key) && !mac.contains(key) && !status.contains(key)) {
                    isTarget = false;
                    break;
                }
            }
            if(isTarget) {
                filtedResult.add(result);
                Log.d("ADD", name + "::" + mac);
            }
        }
        sortList();
        Log.d("SORTED", "True");
        Log.d("Results", JSON.toJSONString(resultList));
        Log.d("filtedResult", JSON.toJSONString(filtedResult));


        notifyDataSetChanged();
        Log.d("Notified", "True");
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    void sortList() {
        filtedResult.sort(new Comparator<Result>() {
            @Override
            public int compare(Result o1, Result o2) {
                String mac1 = o1.getDevMac();
                String mac2 = o2.getDevMac();
                for(int i = 0; i < mac1.length(); i++) {
                    if(mac1.charAt(i) < mac2.charAt(i))
                        return -1;
                    else if (mac1.charAt(i) > mac2.charAt(i))
                        return 1;
                }
                return 0;
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void update(@NonNull final List<Result> results) {
        boolean toAdd = true;
        for(Result re : results) {
            for(Result r : resultList) {
                if(re.getDevMac().equals(r.getDevMac())) {
                    toAdd = false;
                    break;
                }
            }
            if(toAdd)
                resultList.add(re);
        }
        filtList(UpdateResultActivity.keyWord);
        sortList();
        notifyDataSetChanged();
    }

    public void clearLists() {
        resultList.clear();
        filtedResult.clear();
    }

    public void clearListView() {
        filtedResult.clear();
    }

}
